<template>
  <div id="mapContainer"></div>
</template>

<script>
export default {
  name: "IMap",
  data() {
    return {
      map: {}
    };
  },
  beforeCreate() {
    // console.log("IMap will be created");
  },

  beforeDestroy() {
    // console.log("IMap will be destroyed");
    window.BMap = null;
    this.map = null;
    console.log(this.map);
  },
  mounted() {
    this.createMap();
  },
  methods: {
    MP() {
      return new Promise(resolve => {
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.src =
          "https://api.map.baidu.com/api?v=2.0&ak=VabOvHDkrrcpgM4DLaFwzGtd9tfzvCVO&callback=init";
        document.body.appendChild(script);
        window.init = () => {
          resolve(window.BMap);
        };
      });
    },
    createMap() {
      this.MP().then(BMap => {
        this.map = new BMap.Map("mapContainer");
        this.map.clearOverlays();
        // 创建地图实例
        let point = new BMap.Point(116.404, 39.915);
        this.map.centerAndZoom(point, 14);
        this.map.enableScrollWheelZoom(true);
        //添加控件
        this.map.addControl(
          new BMap.NavigationControl({ type: BMAP_NAVIGATION_CONTROL_ZOOM })
        );
        this.map.addControl(
          new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_RIGHT })
        );
        // 创建点标记
        let marker1 = new BMap.Marker(new BMap.Point(116.404, 39.925));
        let marker2 = new BMap.Marker(new BMap.Point(116.404, 39.915));
        let marker3 = new BMap.Marker(new BMap.Point(116.395, 39.935));
        let marker4 = new BMap.Marker(new BMap.Point(116.415, 39.931));
        // 在地图上添加点标记
        this.map.addOverlay(marker1);
        this.map.addOverlay(marker2);
        this.map.addOverlay(marker3);
        this.map.addOverlay(marker4);
      });
    }
  }
};
</script>

<style lang="stylus" scoped>
#mapContainer
    width 500px
    height 500px
    border: 2px solid black
</style>
